home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 17 / CU Amiga Magazine's Super CD-ROM 17 (1997)(EMAP Images)(GB)[!][issue 1997-12].iso / CUCD / Sound / MusicIn / encode.c < prev    next >
C/C++ Source or Header  |  1997-09-23  |  54KB  |  1,577 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. encode.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress          *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com          *
  10.  *                                      *
  11.  * VERSION 3.9t                               *
  12.  *   changes made since last update:                      *
  13.  *   date   programmers     comment                   *
  14.  * 3/01/91  Douglas Wong,    start of version 1.1 records          *
  15.  *        Davis Pan                              *
  16.  * 3/06/91  Douglas Wong    rename: setup.h to endef.h          *
  17.  *                    efilter to enfilter          *
  18.  *                    ewindow to enwindow          *
  19.  *                integrated "quantizer", "scalefactor",*
  20.  *                and "transmission" files              *
  21.  *                update routine "window_subband"       *
  22.  * 3/31/91  Bill Aspromonte    replaced read_filter by           *
  23.  *                create_an_filter              *
  24.  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.          *
  25.  *                Incorporated Jean-Georges Fritsch's   *
  26.  *                "bitstream.c" package.                *
  27.  *                Incorporated Bill Aspromonte's        *
  28.  *                filterbank coefficient matrix          *
  29.  *                calculation routines and added          *
  30.  *                roundoff to coincide with specs.      *
  31.  *                Modified to strictly adhere to          *
  32.  *                encoded bitstream specs, including    *
  33.  *                "Berlin changes".                     *
  34.  *                Modified PCM sound file handling to   *
  35.  *                process all incoming samples and fill *
  36.  *                out last encoded frame with zeros     *
  37.  *                (silence) if needed.              *
  38.  *                Located and fixed numerous software   *
  39.  *                bugs and table data errors.          *
  40.  * 19jun91  dpwe (Aware)    moved "alloc_*" reader to common.c    *
  41.  *                Globals sblimit, alloc replaced by new*
  42.  *                struct 'frame_params' passed as arg.  *
  43.  *                Added JOINT STEREO coding, layers I,II*
  44.  *                Affects: *_bit_allocation,          *
  45.  *                subband_quantization, encode_bit_alloc*
  46.  *                sample_encoding               *
  47.  * 6/10/91  Earle Jennings    modified II_subband_quantization to   *
  48.  *                resolve type cast problem for MS_DOS  *
  49.  * 6/11/91  Earle Jennings    modified to avoid overflow on MS_DOS  *
  50.  *                in routine filter_subband          *
  51.  * 7/10/91  Earle Jennings    port to MsDos from MacIntosh version  *
  52.  * 8/ 8/91  Jens Spille     Change for MS-C6.00              *
  53.  *10/ 1/91  S.I. Sudharsanan,    Ported to IBM AIX platform.          *
  54.  *        Don H. Lee,                           *
  55.  *        Peter W. Farrett                          *
  56.  *10/ 3/91  Don H. Lee        implemented CRC-16 error protection   *
  57.  *                newly introduced function encode_CRC  *
  58.  *11/ 8/91  Kathy Wang        Documentation of code              *
  59.  *                All variablenames are referred to     *
  60.  *                with surrounding pound (#) signs      *
  61.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  62.  *                important fixes involved changing     *
  63.  *                16-bit ints to long or unsigned in    *
  64.  *                bit alloc routines for quant of 65535 *
  65.  *                and passing proper function args.     *
  66.  *                Removed "Other Joint Stereo" option   *
  67.  *                and made bitrate be total channel     *
  68.  *                bitrate, irrespective of the mode.    *
  69.  *                Fixed many small bugs & reorganized.  *
  70.  * 6/16/92  Shaun Astarabadi    Changed I_scale_factor_calc() and     *
  71.  *                II_scale_factor_calc() to use scale   *
  72.  *                factor 0 thru 62 only and not to      *
  73.  *                encode index 63 into the bit stream.  *
  74.  * 7/27/92  Mike Li        (re-)Port to MS-DOS              *
  75.  * 9/22/92  jddevine@aware.com    Fixed _scale_factor_calc() defs       *
  76.  * 3/31/93  Giogio Dimino    changed II_a_bit_allocation() from:   *
  77.  *                if( ad > ...) to if(ad >= ...)          *
  78.  * 8/05/93  TEST        changed I_a_bit_allocation() from:    *
  79.  *                if( ad > ...) to if(ad >= ...)          *
  80.  * 14/07/95 Stephane TAVENARD   Optimized filter_subband, mod -> fabs *
  81.  * 29/11/95 Stephane TAVENARD   Corrected bug in opt. of filter       *
  82.  * 18/09/97 Henryk Richter      optimized window_subband
  83.  **********************************************************************/
  84.  
  85. #define ST_OPTIMIZE
  86. #define Buggs_OPTIMIZE
  87.  
  88. #include "common.h"
  89. #include "encoder.h"
  90.  
  91. #ifdef Buggs_OPTIMIZE
  92. #include "Asmfuncs.h"
  93. #endif
  94.  
  95. #ifdef MS_DOS
  96. extern unsigned _stklen = 16384;
  97. #endif
  98.  
  99.  
  100. /*=======================================================================\
  101. |                                    |
  102. | This segment contains all the core routines of the encoder,        |
  103. | except for the psychoacoustic models.                 |
  104. |                                    |
  105. | The user can select either one of the two psychoacoustic        |
  106. | models. Model I is a simple tonal and noise masking threshold     |
  107. | generator, and Model II is a more sophisticated cochlear masking    |
  108. | threshold generator. Model I is recommended for lower complexity    |
  109. | applications whereas Model II gives better subjective quality at low    |
  110. | bit rates.                                |
  111. |                                    |
  112. | Layers I and II of mono, stereo, and joint stereo modes are supported.|
  113. | Routines associated with a given layer are prefixed by "I_" for layer |
  114. | 1 and "II_" for layer 2.                                              |
  115. \=======================================================================*/
  116.  
  117. /************************************************************************/
  118. /*                                    */
  119. /* read_samples()                            */
  120. /*                                    */
  121. /* PURPOSE:  reads the PCM samples from a file to the buffer        */
  122. /*                                    */
  123. /*  SEMANTICS:                                */
  124. /* Reads #samples_read# number of shorts from #musicin# filepointer    */
  125. /* into #sample_buffer[]#.  Returns the number of samples read.     */
  126. /*                                    */
  127. /************************************************************************/
  128.  
  129. /* #define SAVE_SAMPLES_READ */
  130. #define READ_BUFFER_SIZE 65536
  131.  
  132. unsigned long read_samples(musicin, sample_buffer, num_samples, frame_size)
  133. FILE *musicin;
  134. short sample_buffer[2304];
  135. unsigned long num_samples, frame_size;
  136. {
  137.     unsigned long samples_read;
  138.     static unsigned long samples_to_read;
  139.     static char init = TRUE;
  140.     static short *buffer = NULL;
  141.     static short *buffer_ptr;
  142.     static unsigned long buffer_size = 0;
  143. #ifdef SAVE_SAMPLES_READ
  144.     static FILE *sampleout_file = NULL;
  145. #endif
  146.     if (init) {
  147.     samples_to_read = num_samples;
  148.     init = FALSE;
  149.         buffer = (short *)malloc( READ_BUFFER_SIZE * sizeof( short ) );
  150.         if( !buffer ) {
  151.            fprintf( stderr, "Not enough memory to allocate read buffer !\n" );
  152.            exit( 0 );
  153.         }
  154.         buffer_ptr = buffer;
  155. #ifdef SAVE_SAMPLES_READ
  156.         sampleout_file = fopen( "ram:samples_read", "w" );
  157. #endif
  158.      }
  159.     if (samples_to_read >= frame_size)
  160.     samples_read = frame_size;
  161.     else
  162.     samples_read = samples_to_read;
  163.  
  164.     {
  165.        short *b;
  166.        unsigned long remain_size;
  167.        unsigned long size;
  168.        
  169.        b = sample_buffer;
  170.        remain_size = samples_read;
  171.        samples_read = 0;
  172.        
  173.        do {
  174.           if( buffer_size == 0 ) {
  175.               buffer_size = fread( buffer, sizeof( short ), READ_BUFFER_SIZE, musicin );
  176.               buffer_ptr = buffer;
  177.           }
  178.           if( buffer_size > 0 ) {
  179.               size = remain_size;
  180.               if( size > buffer_size ) size = buffer_size;
  181.               memcpy( b, buffer_ptr, size * sizeof( short ) );
  182.               b += size;
  183.               buffer_ptr += size;
  184.               buffer_size -= size;
  185.               remain_size -= size;
  186.               samples_read += size;
  187.           }
  188.           else {
  189.               remain_size = 0;
  190.           }
  191.        } while( remain_size > 0 );
  192.     }
  193. #if 0    
  194.     if ((samples_read =
  195.      fread(sample_buffer, sizeof(short), (int)samples_read, musicin)) == 0)
  196.     printf("Hit end of audio data\n");
  197. #endif        
  198.     samples_to_read -= samples_read;
  199.     if (samples_read < frame_size && samples_read > 0) {
  200.     printf("Insufficient PCM input for one frame - fillout with zeros\n");
  201.     for (; samples_read < frame_size; sample_buffer[samples_read++] = 0);
  202.     samples_to_read = 0;
  203.     }
  204. #ifdef SAVE_SAMPLES_READ
  205.     if( sampleout_file )
  206.        fwrite( sample_buffer, sizeof(short), (int)samples_read, sampleout_file );
  207. #endif     
  208.     return(samples_read);
  209. }
  210.  
  211. /*****************************************************************************/
  212. /*                                         */
  213. /* get_audio()                                     */
  214. /*                                         */
  215. /* PURPOSE:  reads a frame of audio data from a file to the buffer,         */
  216. /*   aligns the data for future processing, and separates the             */
  217. /*   left and right channels                             */
  218. /*                                         */
  219. /*  SEMANTICS:                                     */
  220. /* Calls read_samples() to read a frame of audio data from filepointer         */
  221. /* #musicin# to #insampl[]#.  The data is shifted to make sure the data      */
  222. /* is centered for the 1024pt window to be used by the psychoacoustic model, */
  223. /* and to compensate for the 256 sample delay from the afilter bank. For      */
  224. /* stereo, the channels are also demultiplexed into #buffer[0][]# and         */
  225. /* #buffer[1][]#                                 */
  226. /*                                         */
  227. /*****************************************************************************/
  228.  
  229. unsigned long get_audio(musicin, buffer, num_samples, stereo, lay)
  230. FILE *musicin;
  231. short FAR buffer[2][1152];
  232. unsigned long num_samples;
  233. int stereo, lay;
  234. {
  235.    int j;
  236.    short insamp[2304];
  237.    unsigned long samples_read;
  238.  
  239.    if (lay == 1){
  240.       if(stereo == 2){ /* layer 1, stereo */
  241.      samples_read = read_samples(musicin, insamp, num_samples,
  242.                      (unsigned long) 768);
  243.      for(j=0;j<448;j++) {
  244.         if(j<64) {
  245.            buffer[0][j] = buffer[0][j+384];
  246.            buffer[1][j] = buffer[1][j+384];
  247.         }
  248.         else {
  249.            buffer[0][j] = insamp[2*j-128];
  250.            buffer[1][j] = insamp[2*j-127];
  251.         }
  252.      }
  253.       }
  254.       else { /* layer 1, mono */
  255.      samples_read = read_samples(musicin, insamp, num_samples,
  256.                      (unsigned long) 384);
  257.      for(j=0;j<448;j++){
  258.         if(j<64) {
  259.            buffer[0][j] = buffer[0][j+384];
  260.            buffer[1][j] = 0;
  261.         }
  262.         else {
  263.            buffer[0][j] = insamp[j-64];
  264.            buffer[1][j] = 0;
  265.         }
  266.      }
  267.       }
  268.    }
  269.    else {
  270.       if(stereo == 2){ /* layer 2 (or 3), stereo */
  271.      samples_read = read_samples(musicin, insamp, num_samples,
  272.                      (unsigned long) 2304);
  273.      for(j=0;j<1152;j++) {
  274.         buffer[0][j] = insamp[2*j];
  275.         buffer[1][j] = insamp[2*j+1];
  276.      }
  277.       }
  278.       else { /* layer 2 (or 3), mono */
  279.      samples_read = read_samples(musicin, insamp, num_samples,
  280.                      (unsigned long) 1152);
  281.      for(j=0;j<1152;j++){
  282.         buffer[0][j] = insamp[j];
  283.         buffer[1][j] = 0;
  284.      }
  285.       }
  286.    }
  287.    return(samples_read);
  288. }
  289.  
  290. /************************************************************************/
  291. /*                                    */
  292. /* read_ana_window()                            */
  293. /*                                    */
  294. /* PURPOSE:  Reads encoder window file "enwindow" into array #ana_win#  */
  295. /*                                    */
  296. /************************************************************************/
  297.  
  298. void read_ana_window(ana_win)
  299. double FAR ana_win[HAN_SIZE];
  300. {
  301.     int i,j[4];
  302.     FILE *fp;
  303.     double f[4];
  304.     char t[150];
  305.  
  306.     if (!(fp = OpenTableFile("enwindow") ) ) {
  307.        printf("Please check analysis window table 'enwindow'\n");
  308.        exit(1);
  309.     }
  310.     for (i=0;i<512;i+=4) {
  311.        fgets(t, 150, fp);
  312.        /* ST 10/04/1995 -> spaces suppressed ! -> DICE comp. */
  313.        sscanf(t,"C[%d]=%lf C[%d]=%lf C[%d]=%lf C[%d]=%lf\n",
  314.           j, f,j+1,f+1,j+2,f+2,j+3,f+3);
  315.        if (i==j[0]) {
  316.       ana_win[i] = f[0];
  317.       ana_win[i+1] = f[1];
  318.       ana_win[i+2] = f[2];
  319.       ana_win[i+3] = f[3];
  320. //printf( "%d %f\n%d %f\n%d %f\n%d %f\n",
  321. //      i, f[0], i+1, f[1], i+2, f[2], i+3, f[3] );
  322.        }
  323.        else {
  324.       printf("Check index in analysis window table\n");
  325.       exit(1);
  326.        }
  327.        fgets(t,150,fp);
  328.     }
  329.    fclose(fp);
  330. /*
  331. {
  332.  int i,j;
  333.  double s;
  334.  
  335.  for( i=0; i<64; i++ ) {
  336.    s = 0.0;
  337.    for( j=0; j<8; j++ ) {
  338.       s += ana_win[ i + j*64 ];
  339.    }
  340.    printf( "%d %f\n", i, s );
  341.  }
  342.  exit( 0 );
  343. }
  344. */
  345.  
  346. }
  347.  
  348. /*************************************************************************/
  349. /*                                     */
  350. /* window_subband()                             */
  351. /*                                     */
  352. /* PURPOSE:  Overlapping window on PCM samples                 */
  353. /*                                     */
  354. /* SEMANTICS:                                 */
  355. /* 32 16-bit pcm samples are scaled to fractional 2's complement and     */
  356. /* concatenated to the end of the window buffer #x#. The updated window  */
  357. /* buffer #x# is then windowed by the analysis window #c# to produce the */
  358. /* windowed sample #z#                             */
  359. /*                                     */
  360. /*************************************************************************/
  361.  
  362. void window_subband(buffer, z, k)
  363. short FAR **buffer;
  364. double FAR z[HAN_SIZE];
  365. int k;
  366. {
  367.     typedef double FAR XX[2][HAN_SIZE];
  368.     static XX FAR *x;
  369.     register int i, j; /* ST 15/07/95 : Added register */
  370.     static off[2] = {0,0};
  371.     static char init = 0;
  372.     static double FAR *c;
  373. #ifdef ST_OPTIMIZE /* ST 15/07/95 */
  374.     double *xk, *xm, *zi, *ci;
  375. #endif    
  376.  
  377.     if (!init) {
  378.     c = (double FAR *) mem_alloc(sizeof(double) * HAN_SIZE, "window");
  379.     read_ana_window(c);
  380.     x = (XX FAR *) mem_alloc(sizeof(XX),"x");
  381.     for (i=0;i<2;i++)
  382.         for (j=0;j<HAN_SIZE;j++)
  383.         (*x)[i][j] = 0;
  384.     init = 1;
  385.     }
  386.  
  387. #ifdef ST_OPTIMIZE /* ST 15/07/95 */
  388.     /* replace 32 oldest samples with 32 new samples */
  389.     xk = &(*x)[ k ][ 31 + off[ k ] ];
  390.  
  391. #ifdef Buggs_OPTIMIZE
  392.     ASM_FastReplace( xk, *buffer, 32 );
  393.     *buffer += 32;
  394. #else
  395.     for( i=0; i<32; i++ ) {
  396.        *xk-- = ((double) *(*buffer)++) / SCALE; // replace with * 1/SCALE fmul is >10 times faster than fdiv
  397.     }
  398.     /* shift samples into proper window positions */
  399. #endif
  400.  
  401.     zi = z;
  402.     ci = c;
  403. #if 0
  404.     xk = &(*x)[ k ][ off[ k ] ];
  405.     xm = &(*x)[ k ][ HAN_SIZE-1 ];    
  406.     for( i=0; i<HAN_SIZE; i++ ) {
  407.        *zi++ = *xk++ * *ci++;
  408.        if( xk > xm ) {
  409.           xk = &(*x)[ k ][ 0 ];
  410.        }
  411.     }
  412. #else
  413.     xk = &(*x)[ k ][ off[ k ] ];
  414. //    xm = &(*x)[ k ][ HAN_SIZE-1 ];
  415.     i = HAN_SIZE - off[ k ];
  416.     while( i-- ) *zi++ = *xk++ * *ci++;
  417.     i = off[ k ];
  418.     if( i > 0 ) {
  419.        xk = &(*x)[ k ][ 0 ];
  420.        while( i-- ) *zi++ = *xk++ * *ci++;
  421.     }
  422. #endif
  423.     off[ k ] += 480;        /*offset is modulo (HAN_SIZE-1)*/
  424.     off[ k ] &= HAN_SIZE-1;
  425. #else
  426.     /* replace 32 oldest samples with 32 new samples */
  427.     for (i=0;i<32;i++) (*x)[k][31-i+off[k]] = (double) *(*buffer)++/SCALE;
  428.     /* shift samples into proper window positions */
  429.     for (i=0;i<HAN_SIZE;i++) z[i] = (*x)[k][(i+off[k])&HAN_SIZE-1] * c[i];
  430.     off[k] += 480;        /*offset is modulo (HAN_SIZE-1)*/
  431.     off[k] &= HAN_SIZE-1;
  432. #endif
  433.  
  434. }
  435.  
  436. /************************************************************************/
  437. /*                                    */
  438. /* create_ana_afilter()                            */
  439. /*                                    */
  440. /* PURPOSE:  Calculates the analysis filter bank coefficients        */
  441. /*                                    */
  442. /* SEMANTICS:                                */
  443. /* Calculates the analysis filterbank coefficients and rounds to the    */
  444. /* 9th decimal place accuracy of the filterbank tables in the ISO    */
  445. /* document.  The coefficients are stored in #filter#            */
  446. /*                                    */
  447. /************************************************************************/
  448.  
  449. void create_ana_filter(filter)
  450. double FAR filter[SBLIMIT][64];
  451. {
  452.    register int i,k;
  453.  
  454.    for (i=0; i<32; i++)
  455.       for (k=0; k<64; k++) {
  456.       if ((filter[i][k] = 1e9*cos((double)((2*i+1)*(16-k)*PI64))) >= 0)
  457.          modf(filter[i][k]+0.5, &filter[i][k]);
  458.       else
  459.          modf(filter[i][k]-0.5, &filter[i][k]);
  460.       filter[i][k] *= 1e-9;
  461. /*      printf( "%d,%d  =  %f\n", i, k, filter[i][k] ); */
  462.    }
  463. }
  464.  
  465. /******************************************************************************/
  466. /*                                          */
  467. /* filter_subband()                                  */
  468. /*                                          */
  469. /* PURPOSE:  Calculates the analysis filter bank coefficients              */
  470. /*                                          */
  471. /* SEMANTICS:                                      */
  472. /*    The windowed samples #z# is filtered by the digital filter matrix #m# */
  473. /* to produce the subband samples #s#. This done by first selectively          */
  474. /* picking out values from the windowed samples, and then multiplying          */
  475. /* them by the filter matrix, producing 32 subband samples.              */
  476. /*                                          */
  477. /******************************************************************************/
  478.  
  479. void filter_subband(z,s)
  480. double FAR z[HAN_SIZE], s[SBLIMIT];
  481. {
  482.    double y[64];
  483.    register int i,j;    /* ST 14/07/95 : Added register */
  484. static char init = 0;
  485.    typedef double MM[SBLIMIT][64];
  486. static MM FAR *m;
  487. #ifdef ST_OPTIMIZE      /* ST 14/07/95 */
  488.    double ysum[ 16 ], ysub[ 16 ];
  489.    double *fe, *ys, *zi;
  490.    double si;
  491. #endif
  492.  
  493. #ifdef MS_DOS
  494.    long    SIZE_OF_MM;
  495.    SIZE_OF_MM       = SBLIMIT*64;
  496.    SIZE_OF_MM       *= 8;
  497.    if (!init) {
  498.        m = (MM FAR *) mem_alloc(SIZE_OF_MM, "filter");
  499.        create_ana_filter(*m);
  500.        init = 1;
  501.    }
  502. #else
  503.    if (!init) {
  504.        m = (MM FAR *) mem_alloc(sizeof(MM), "filter");
  505.        create_ana_filter(*m);
  506.        init = 1;
  507.    }
  508. #endif
  509. #ifdef ST_OPTIMIZE      /* ST 14/07/95 */
  510.  
  511. /*   for( i=0; i<64; i++ ) for (j=0, y[i] = 0;j<8;j++) y[i] += z[i+64*j]; */
  512.    zi = z;
  513.    for( i=0; i<64; i++ ) {
  514.       y[ i ] = *zi + zi[ 64 ] + zi[ 128 ] + zi[ 192 ] +
  515.                zi[ 256 ] + zi[ 320 ] + zi[ 384 ] + zi[ 448 ];
  516.       zi++;
  517.    }
  518.    for( i=0; i<16; i++ ) ysum[ i ] = y[ i ] + y[ 32-i ];
  519.    for( i=0; i<15; i++ ) ysub[ i ] = y[ 33+i ] - y[ 63-i ];
  520.    for( i=0; i<SBLIMIT; i++ ) {
  521.       fe = &((*m)[ i ][ 0 ]);
  522.       si = y[ 16 ];
  523.       ys = ysum;
  524.       for( j=0; j<16; j++ ) si += *fe++ * *ys++;
  525.       fe += 17;
  526.       ys = ysub;
  527.       for( j=0; j<15; j++ ) si += *fe++ * *ys++; /* ST 29/11/95 - 14->15 */
  528.       s[ i ] = si;
  529.    }
  530. #else
  531.    for (i=0;i<64;i++) for (j=0, y[i] = 0;j<8;j++) y[i] += z[i+64*j];
  532.    for (i=0;i<SBLIMIT;i++)
  533.        for (j=0, s[i]= 0;j<64;j++) s[i] += (*m)[i][j] * y[j];
  534. #endif  
  535. }
  536.  
  537. /************************************************************************/
  538. /*                                    */
  539. /* encode_info()                            */
  540. /*                                    */
  541. /* PURPOSE:  Puts the syncword and header information on the output    */
  542. /* bitstream.                                */
  543. /*                                    */
  544. /************************************************************************/
  545.  
  546. void encode_info(fr_ps,bs)
  547. frame_params *fr_ps;
  548. Bit_stream_struc *bs;
  549. {
  550.     layer *info = fr_ps->header;
  551.  
  552.     putbits(bs,0xfff,12);             /* syncword 12 bits */
  553.     put1bit(bs,info->version);         /* ID          1 bit  */
  554.     putbits(bs,4-info->lay,2);         /* layer     2 bits */
  555.     put1bit(bs,!info->error_protection);     /* bit set => no err prot */
  556.     putbits(bs,info->bitrate_index,4);
  557.     putbits(bs,info->sampling_frequency,2);
  558.     put1bit(bs,info->padding);
  559.     put1bit(bs,info->extension);         /* private_bit */
  560.     putbits(bs,info->mode,2);
  561.     putbits(bs,info->mode_ext,2);
  562.     put1bit(bs,info->copyright);
  563.     put1bit(bs,info->original);
  564.     putbits(bs,info->emphasis,2);
  565. }
  566.  
  567. /************************************************************************/
  568. /*                                    */
  569. /* mod()                                */
  570. /*                                    */
  571. /* PURPOSE:  Returns the absolute value of its argument         */
  572. /*                                    */
  573. /************************************************************************/
  574.  
  575. #ifdef ST_OPTIMIZE      /* ST 14/07/95 */
  576. #define mod(a) fabs(a)
  577. #else
  578. double mod(a)
  579. double a;
  580. {
  581.     return (a > 0) ? a : -a;
  582. }
  583. #endif
  584.  
  585. /*************************************************************************/
  586. /*                                     */
  587. /* I_combine_LR    (Layer I)                         */
  588. /* II_combine_LR   (Layer II)                         */
  589. /*                                     */
  590. /* PURPOSE:Combines left and right channels into a mono channel      */
  591. /*                                     */
  592. /* SEMANTICS:  The average of left and right subband samples is put into */
  593. /* #joint_sample#                             */
  594. /*                                     */
  595. /* Layer I and II differ in frame length and # subbands used         */
  596. /*                                     */
  597. /*************************************************************************/
  598.  
  599. void I_combine_LR(sb_sample, joint_sample)
  600. double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
  601. double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT];
  602. {   /* make a filtered mono for joint stereo */
  603.     int sb, smp;
  604.  
  605.    for(sb = 0; sb<SBLIMIT; ++sb)
  606.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  607.     joint_sample[0][smp][sb] = .5 *
  608.             (sb_sample[0][0][smp][sb] + sb_sample[1][0][smp][sb]);
  609. }
  610.  
  611. void II_combine_LR(sb_sample, joint_sample, sblimit)
  612. double FAR sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
  613. double FAR joint_sample[3][SCALE_BLOCK][SBLIMIT];
  614. int sblimit;
  615. {  /* make a filtered mono for joint stereo */
  616.    int sb, smp, sufr;
  617.  
  618.    for(sb = 0; sb<sblimit; ++sb)
  619.       for(smp = 0; smp<SCALE_BLOCK; ++smp)
  620.      for(sufr = 0; sufr<3; ++sufr)
  621.         joint_sample[sufr][smp][sb] = .5 * (sb_sample[0][sufr][smp][sb]
  622.                        + sb_sample[1][sufr][smp][sb]);
  623. }
  624.  
  625. /************************************************************************/
  626. /*                                    */
  627. /* I_scale_factor_calc       (Layer I)                    */
  628. /* II_scale_factor_calc    (Layer II)                    */
  629. /*                                    */
  630. /* PURPOSE:For each subband, calculate the scale factor for each set    */
  631. /* of the 12 subband samples                        */
  632. /*                                    */
  633. /* SEMANTICS:  Pick the scalefactor #multiple[]# just larger than the    */
  634. /* absolute value of the peak subband sample of 12 samples,        */
  635. /* and store the corresponding scalefactor index in #scalar#.        */
  636. /*                                    */
  637. /* Layer II has three sets of 12-subband samples for a given        */
  638. /* subband.                                */
  639. /*                                    */
  640. /************************************************************************/
  641.  
  642. void I_scale_factor_calc(sb_sample,scalar,stereo)
  643. double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT];
  644. unsigned int scalar[][3][SBLIMIT];
  645. int stereo;
  646. {
  647.    int i,j, k;
  648.    double s[SBLIMIT];
  649.  
  650.    for (k=0;k<stereo;k++) {
  651.      for (i=0;i<SBLIMIT;i++)
  652.        for (j=1, s[i] = mod(sb_sample[k][0][0][i]);j<SCALE_BLOCK;j++)
  653.      if (mod(sb_sample[k][0][j][i]) > s[i])
  654.         s[i] = mod(sb_sample[k][0][j][i]);
  655.  
  656.      for (i=0;i<SBLIMIT;i++)
  657.        for (j=SCALE_RANGE-2,scalar[k][0][i]=0;j>=0;j--) /* $A 6/16/92 */
  658.      if (s[i] <= multiple[j]) {
  659.         scalar[k][0][i] = j;
  660.         break;
  661.      }
  662.    }
  663. }
  664.  
  665. /******************************** Layer II ******************************/
  666.  
  667. void II_scale_factor_calc(sb_sample,scalar,stereo,sblimit)
  668. double FAR sb_sample[][3][SCALE_BLOCK][SBLIMIT];
  669. unsigned int scalar[][3][SBLIMIT];
  670. int stereo,sblimit;
  671. {
  672.   int i,j, k,t;
  673.   double s[SBLIMIT];
  674.  
  675.   for (k=0;k<stereo;k++) for (t=0;t<3;t++) {
  676.     for (i=0;i<sblimit;i++)
  677.       for (j=1, s[i] = mod(sb_sample[k][t][0][i]);j<SCALE_BLOCK;j++)
  678.     if (mod(sb_sample[k][t][j][i]) > s[i])
  679.          s[i] = mod(sb_sample[k][t][j][i]);
  680.  
  681.     for (i=0;i<sblimit;i++)
  682.       for (j=SCALE_RANGE-2,scalar[k][t][i]=0;j>=0;j--)      /* $A 6/16/92 */
  683.     if (s[i] <= multiple[j]) {
  684.        scalar[k][t][i] = j;
  685.        break;
  686.     }
  687.       for (i=sblimit;i<SBLIMIT;i++) scalar[k][t][i] = SCALE_RANGE-1;
  688.   }
  689. }
  690.  
  691. /************************************************************************/
  692. /*                                    */
  693. /* pick_scale  (Layer II)                        */
  694. /*                                    */
  695. /* PURPOSE:For each subband, puts the smallest scalefactor of the 3    */
  696. /* associated with a frame into #max_sc#.  This is used         */
  697. /* used by Psychoacoustic Model I.                    */
  698. /* (I would recommend changin max_sc to min_sc)             */
  699. /*                                    */
  700. /************************************************************************/
  701.  
  702. void pick_scale(scalar, fr_ps, max_sc)
  703. unsigned int scalar[2][3][SBLIMIT];
  704. frame_params *fr_ps;
  705. double FAR max_sc[2][SBLIMIT];
  706. {
  707.   int i,j,k,max;
  708.   int stereo  = fr_ps->stereo;
  709.   int sblimit = fr_ps->sblimit;
  710.  
  711.   for (k=0;k<stereo;k++)
  712.     for (i=0;i<sblimit;max_sc[k][i] = multiple[max],i++)
  713.       for (j=1, max = scalar[k][0][i];j<3;j++)
  714.      if (max > scalar[k][j][i]) max = scalar[k][j][i];
  715.   for (i=sblimit;i<SBLIMIT;i++) max_sc[0][i] = max_sc[1][i] = 1E-20;
  716. }
  717.  
  718. /************************************************************************/
  719. /*                                    */
  720. /* put_scale   (Layer I)                        */
  721. /*                                    */
  722. /* PURPOSE:Sets #max_sc# to the scalefactor index in #scalar.        */
  723. /* This is used by Psychoacoustic Model I                */
  724. /*                                    */
  725. /************************************************************************/
  726.  
  727. void put_scale(scalar, fr_ps, max_sc)
  728. unsigned int scalar[2][3][SBLIMIT];
  729. frame_params *fr_ps;
  730. double FAR max_sc[2][SBLIMIT];
  731. {
  732.    int i,k /*, max*/ ;
  733.    int stereo  = fr_ps->stereo;
  734. //   int sblimit = fr_ps->sblimit;
  735.  
  736.    for (k=0;k<stereo;k++) for (i=0;i<SBLIMIT;i++)
  737.     max_sc[k][i] = multiple[scalar[k][0][i]];
  738. }
  739.  
  740. /**************************************************************************/
  741. /*                                      */
  742. /* II_transmission_pattern (Layer II only)                  */
  743. /*                                      */
  744. /* PURPOSE:For a given subband, determines whether to send 1, 2, or      */
  745. /* all 3 of the scalefactors, and fills in the scalefactor          */
  746. /* select information accordingly                      */
  747. /*                                      */
  748. /* SEMANTICS:  The subbands and channels are classified based on how much */
  749. /* the scalefactors changes over its three values (corresponding      */
  750. /* to the 3 sets of 12 samples per subband).  The classification      */
  751. /* will send 1 or 2 scalefactors instead of three if the scalefactors      */
  752. /* do not change much.    The scalefactor select information,          */
  753. /* #scfsi#, is filled in accordingly.                      */
  754. /*                                      */
  755. /**************************************************************************/
  756.  
  757. void II_transmission_pattern(scalar, scfsi, fr_ps)
  758. unsigned int scalar[2][3][SBLIMIT];
  759. unsigned int scfsi[2][SBLIMIT];
  760. frame_params *fr_ps;
  761. {
  762.    int stereo  = fr_ps->stereo;
  763.    int sblimit = fr_ps->sblimit;
  764.    int dscf[2];
  765.    int class[2],i,j,k;
  766. static int pattern[5][5] = {0x123, 0x122, 0x122, 0x133, 0x123,
  767.                 0x113, 0x111, 0x111, 0x444, 0x113,
  768.                 0x111, 0x111, 0x111, 0x333, 0x113,
  769.                 0x222, 0x222, 0x222, 0x333, 0x123,
  770.                 0x123, 0x122, 0x122, 0x133, 0x123};
  771.  
  772.    for (k=0;k<stereo;k++)
  773.      for (i=0;i<sblimit;i++) {
  774.        dscf[0] =  (scalar[k][0][i]-scalar[k][1][i]);
  775.        dscf[1] =  (scalar[k][1][i]-scalar[k][2][i]);
  776.        for (j=0;j<2;j++) {
  777.      if (dscf[j]<=-3) class[j] = 0;
  778.      else if (dscf[j] > -3 && dscf[j] <0) class[j] = 1;
  779.           else if (dscf[j] == 0) class[j] = 2;
  780.            else if (dscf[j] > 0 && dscf[j] < 3) class[j] = 3;
  781.             else class[j] = 4;
  782.        }
  783.        switch (pattern[class[0]][class[1]]) {
  784.      case 0x123 :     scfsi[k][i] = 0;
  785.              break;
  786.      case 0x122 :     scfsi[k][i] = 3;
  787.              scalar[k][2][i] = scalar[k][1][i];
  788.              break;
  789.      case 0x133 :     scfsi[k][i] = 3;
  790.              scalar[k][1][i] = scalar[k][2][i];
  791.              break;
  792.      case 0x113 :     scfsi[k][i] = 1;
  793.              scalar[k][1][i] = scalar[k][0][i];
  794.              break;
  795.      case 0x111 :     scfsi[k][i] = 2;
  796.              scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  797.              break;
  798.      case 0x222 :     scfsi[k][i] = 2;
  799.              scalar[k][0][i] = scalar[k][2][i] = scalar[k][1][i];
  800.              break;
  801.      case 0x333 :     scfsi[k][i] = 2;
  802.              scalar[k][0][i] = scalar[k][1][i] = scalar[k][2][i];
  803.              break;
  804.      case 0x444 :     scfsi[k][i] = 2;
  805.              if (scalar[k][0][i] > scalar[k][2][i])
  806.                   scalar[k][0][i] = scalar[k][2][i];
  807.              scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
  808.       }
  809.    }
  810. }
  811.  
  812. /************************************************************************/
  813. /*                                    */
  814. /* I_encode_scale  (Layer I)                        */
  815. /* II_encode_scale (Layer II)                        */
  816. /*                                    */
  817. /* PURPOSE:The encoded scalar factor information is arranged and    */
  818. /* queued into the output fifo to be transmitted.            */
  819. /*                                    */
  820. /* For Layer II, the three scale factors associated with        */
  821. /* a given subband and channel are transmitted in accordance        */
  822. /* with the scfsi, which is transmitted first.                */
  823. /*                                    */
  824. /************************************************************************/
  825.  
  826. void I_encode_scale(scalar, bit_alloc, fr_ps, bs)
  827. unsigned int scalar[2][3][SBLIMIT];
  828. unsigned int bit_alloc[2][SBLIMIT];
  829. frame_params *fr_ps;
  830. Bit_stream_struc *bs;
  831. {
  832.    int stereo  = fr_ps->stereo;
  833. //   int sblimit = fr_ps->sblimit;
  834.    int i,j;
  835.  
  836.    for (i=0;i<SBLIMIT;i++) for (j=0;j<stereo;j++)
  837.       if (bit_alloc[j][i]) putbits(bs,scalar[j][0][i],6);
  838. }
  839.  
  840. /***************************** Layer II  ********************************/
  841.  
  842. void II_encode_scale(bit_alloc, scfsi, scalar, fr_ps, bs)
  843. unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  844. unsigned int scalar[2][3][SBLIMIT];
  845. frame_params *fr_ps;
  846. Bit_stream_struc *bs;
  847. {
  848.    int stereo  = fr_ps->stereo;
  849.    int sblimit = fr_ps->sblimit;
  850. //   int jsbound = fr_ps->jsbound;
  851.    int i,j,k;
  852.  
  853.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  854.      if (bit_alloc[k][i])  putbits(bs,scfsi[k][i],2);
  855.  
  856.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  857.      if (bit_alloc[k][i])  /* above jsbound, bit_alloc[0][i] == ba[1][i] */
  858.     switch (scfsi[k][i]) {
  859.        case 0: for (j=0;j<3;j++)
  860.              putbits(bs,scalar[k][j][i],6);
  861.            break;
  862.        case 1:
  863.        case 3: putbits(bs,scalar[k][0][i],6);
  864.            putbits(bs,scalar[k][2][i],6);
  865.            break;
  866.        case 2: putbits(bs,scalar[k][0][i],6);
  867.     }
  868. }
  869.  
  870. /*=======================================================================\
  871. |                                     |
  872. |      The following routines are done after the masking threshold     |
  873. | has been calculated by the fft analysis routines in the Psychoacoustic |
  874. | model. Using the MNR calculated, the actual number of bits allocated     |
  875. | to each subband is found iteratively.                  |
  876. |                                     |
  877. \=======================================================================*/
  878.  
  879. /*************************************************************************/
  880. /*                                     */
  881. /* I_bits_for_nonoise  (Layer I)                     */
  882. /* II_bits_for_nonoise (Layer II)                     */
  883. /*                                     */
  884. /* PURPOSE:Returns the number of bits required to produce a         */
  885. /* mask-to-noise ratio better or equal to the noise/no_noise threshold.  */
  886. /*                                     */
  887. /* SEMANTICS:                                 */
  888. /* bbal = # bits needed for encoding bit allocation             */
  889. /* bsel = # bits needed for encoding scalefactor select information     */
  890. /* banc = # bits needed for ancillary data (header info included)     */
  891. /*                                     */
  892. /* For each subband and channel, will add bits until one of the      */
  893. /* following occurs:                             */
  894. /* - Hit maximum number of bits we can allocate for that subband     */
  895. /* - MNR is better than or equal to the minimum masking level         */
  896. /*   (NOISY_MIN_MNR)                             */
  897. /* Then the bits required for scalefactors, scfsi, bit allocation,     */
  898. /* and the subband samples are tallied (#req_bits#) and returned.     */
  899. /*                                     */
  900. /* (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is     */
  901. /* counted as 'noisy' by the logic which chooses the number of JS        */
  902. /* subbands.                                 */
  903. /*                                     */
  904. /* Joint stereo is supported.                         */
  905. /*                                     */
  906. /*************************************************************************/
  907.  
  908. static double snr[18] = {0.00, 7.00, 11.00, 16.00, 20.84,
  909.              25.28, 31.59, 37.75, 43.84,
  910.              49.89, 55.93, 61.96, 67.98, 74.01,
  911.              80.03, 86.05, 92.01, 98.01};
  912.  
  913. int I_bits_for_nonoise(perm_smr, fr_ps)
  914. double FAR perm_smr[2][SBLIMIT];
  915. frame_params *fr_ps;
  916. {
  917.    int i,j,k;
  918.    int stereo  = fr_ps->stereo;
  919. //   int sblimit = fr_ps->sblimit;
  920.    int jsbound = fr_ps->jsbound;
  921.    int req_bits /* = 0 */;
  922.  
  923.    /* initial b_anc (header) allocation bits */
  924.    req_bits = 32 + 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  925.  
  926.    for(i=0; i<SBLIMIT; ++i)
  927.      for(j=0; j<((i<jsbound)?stereo:1); ++j) {
  928.        for(k=0;k<14; ++k)
  929.      if( (-perm_smr[j][i] + snr[k]) >= NOISY_MIN_MNR)
  930.        break; /* we found enough bits */
  931.      if(stereo == 2 && i >= jsbound)     /* check other JS channel */
  932.        for(;k<14; ++k)
  933.          if( (-perm_smr[1-j][i] + snr[k]) >= NOISY_MIN_MNR) break;
  934.      if(k>0) req_bits += (k+1)*SCALE_BLOCK + 6*((i>=jsbound)?stereo:1);
  935.    }
  936.    return req_bits;
  937. }
  938.  
  939. /***************************** Layer II  ********************************/
  940.  
  941. int II_bits_for_nonoise(perm_smr, scfsi, fr_ps)
  942. double FAR perm_smr[2][SBLIMIT];
  943. unsigned int scfsi[2][SBLIMIT];
  944. frame_params *fr_ps;
  945. {
  946.    int sb,ch,ba;
  947.    int stereo  = fr_ps->stereo;
  948.    int sblimit = fr_ps->sblimit;
  949.    int jsbound = fr_ps->jsbound;
  950.    al_table *alloc = fr_ps->alloc;
  951.    int req_bits /* = 0 */, bbal = 0, berr /*= 0*/, banc = 32;
  952.    int maxAlloc, sel_bits, sc_bits, smp_bits;
  953. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  954.  
  955.    /* added 92-08-11 shn */
  956.    if (fr_ps->header->error_protection) berr=16; else berr=0;
  957.  
  958.    for (sb=0; sb<jsbound; ++sb)
  959.      bbal += stereo * (*alloc)[sb][0].bits;
  960.    for (sb=jsbound; sb<sblimit; ++sb)
  961.      bbal += (*alloc)[sb][0].bits;
  962.    req_bits = banc + bbal + berr;
  963.  
  964.    for(sb=0; sb<sblimit; ++sb)
  965.      for(ch=0; ch<((sb<jsbound)?stereo:1); ++ch) {
  966.        maxAlloc = (1<<(*alloc)[sb][0].bits)-1;
  967.        sel_bits = sc_bits = smp_bits = 0;
  968.        for(ba=0;ba<maxAlloc-1; ++ba)
  969.      if( (-perm_smr[ch][sb] + snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  970.          >= NOISY_MIN_MNR)
  971.         break;    /* we found enough bits */
  972.        if(stereo == 2 && sb >= jsbound) /* check other JS channel */
  973.      for(;ba<maxAlloc-1; ++ba)
  974.        if( (-perm_smr[1-ch][sb]+ snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
  975.            >= NOISY_MIN_MNR)
  976.          break;
  977.        if(ba>0) {
  978.      smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
  979.      /* scale factor bits required for subband */
  980.      sel_bits = 2;
  981.      sc_bits  = 6 * sfsPerScfsi[scfsi[ch][sb]];
  982.      if(stereo == 2 && sb >= jsbound) {
  983.        /* each new js sb has L+R scfsis */
  984.        sel_bits += 2;
  985.        sc_bits  += 6 * sfsPerScfsi[scfsi[1-ch][sb]];
  986.      }
  987.      req_bits += smp_bits+sel_bits+sc_bits;
  988.        }
  989.    }
  990.    return req_bits;
  991. }
  992.  
  993. /*************************************************************************/
  994. /*                                     */
  995. /* I_main_bit_allocation   (Layer I)                     */
  996. /* II_main_bit_allocation  (Layer II)                     */
  997. /*                                     */
  998. /* PURPOSE:For joint stereo mode, determines which of the 4 joint     */
  999. /* stereo modes is needed.  Then calls *_a_bit_allocation(), which     */
  1000. /* allocates bits for each of the subbands until there are no more bits  */
  1001. /* left, or the MNR is at the noise/no_noise threshold.          */
  1002. /*                                     */
  1003. /* SEMANTICS:                                 */
  1004. /*                                     */
  1005. /* For joint stereo mode, joint stereo is changed to stereo if         */
  1006. /* there are enough bits to encode stereo at or better than the      */
  1007. /* no-noise threshold (NOISY_MIN_MNR).    Otherwise, the system         */
  1008. /* iteratively allocates less bits by using joint stereo until one     */
  1009. /* of the following occurs:                         */
  1010. /* - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)         */
  1011. /* - mode_ext has been reduced to 0, which means that all but the     */
  1012. /*   lowest 4 subbands have been converted from stereo to joint      */
  1013. /*   stereo, and no more subbands may be converted             */
  1014. /*                                     */
  1015. /*     This function calls *_bits_for_nonoise() and *_a_bit_allocation().*/
  1016. /*                                     */
  1017. /*************************************************************************/
  1018.  
  1019. void I_main_bit_allocation(perm_smr, bit_alloc, adb, fr_ps)
  1020. double FAR perm_smr[2][SBLIMIT];
  1021. unsigned int bit_alloc[2][SBLIMIT];
  1022. int *adb;
  1023. frame_params *fr_ps;
  1024. {
  1025.    int    noisy_sbs;
  1026.    int    mode, mode_ext, lay, i;
  1027.    int    rq_db /*, av_db = *adb */;
  1028. static    int init = 0;
  1029.  
  1030.    if(init == 0) {
  1031.      /* rearrange snr for layer I */
  1032.      snr[2] = snr[3];
  1033.      for (i=3;i<16;i++) snr[i] = snr[i+2];
  1034.      init = 1;
  1035.    }
  1036.  
  1037.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  1038.      fr_ps->header->mode = MPG_MD_STEREO;
  1039.      fr_ps->header->mode_ext = 0;
  1040.      fr_ps->jsbound = fr_ps->sblimit;
  1041.      if(rq_db = I_bits_for_nonoise(perm_smr, fr_ps) > *adb) {
  1042.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  1043.        mode_ext = 4;           /* 3 is least severe reduction */
  1044.        lay = fr_ps->header->lay;
  1045.        do {
  1046.       --mode_ext;
  1047.       fr_ps->jsbound = js_bound(lay, mode_ext);
  1048.       rq_db = I_bits_for_nonoise(perm_smr, fr_ps);
  1049.        } while( (rq_db > *adb) && (mode_ext > 0));
  1050.        fr_ps->header->mode_ext = mode_ext;
  1051.      }      /* well we either eliminated noisy sbs or mode_ext == 0 */
  1052.    }
  1053.    noisy_sbs = I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps);
  1054. }
  1055.  
  1056. /***************************** Layer II  ********************************/
  1057.  
  1058. void II_main_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
  1059. double FAR perm_smr[2][SBLIMIT];
  1060. unsigned int scfsi[2][SBLIMIT];
  1061. unsigned int bit_alloc[2][SBLIMIT];
  1062. int *adb;
  1063. frame_params *fr_ps;
  1064. {
  1065.    int    noisy_sbs /*, nn */;
  1066.    int    mode, mode_ext, lay;
  1067.    int    rq_db /* , av_db = *adb */ ;
  1068.  
  1069.    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
  1070.      fr_ps->header->mode = MPG_MD_STEREO;
  1071.      fr_ps->header->mode_ext = 0;
  1072.      fr_ps->jsbound = fr_ps->sblimit;
  1073.      if((rq_db=II_bits_for_nonoise(perm_smr, scfsi, fr_ps)) > *adb) {
  1074.        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
  1075.        mode_ext = 4;           /* 3 is least severe reduction */
  1076.        lay = fr_ps->header->lay;
  1077.        do {
  1078.      --mode_ext;
  1079.      fr_ps->jsbound = js_bound(lay, mode_ext);
  1080.      rq_db = II_bits_for_nonoise(perm_smr, scfsi, fr_ps);
  1081.        } while( (rq_db > *adb) && (mode_ext > 0));
  1082.        fr_ps->header->mode_ext = mode_ext;
  1083.      }      /* well we either eliminated noisy sbs or mode_ext == 0 */
  1084.    }
  1085.    noisy_sbs = II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps);
  1086. }
  1087.  
  1088. /*************************************************************************/
  1089. /*                                     */
  1090. /* I_a_bit_allocation  (Layer I)                     */
  1091. /* II_a_bit_allocation (Layer II)                     */
  1092. /*                                     */
  1093. /* PURPOSE:Adds bits to the subbands with the lowest mask-to-noise     */
  1094. /* ratios, until the maximum number of bits for the subband has      */
  1095. /* been allocated.                             */
  1096. /*                                     */
  1097. /* SEMANTICS:                                 */
  1098. /* 1. Find the subband and channel with the smallest MNR (#min_sb#,     */
  1099. /*    and #min_ch#)                             */
  1100. /* 2. Calculate the increase in bits needed if we increase the bit     */
  1101. /*    allocation to the next higher level                 */
  1102. /* 3. If there are enough bits available for increasing the resolution     */
  1103. /*    in #min_sb#, #min_ch#, and the subband has not yet reached its     */
  1104. /*    maximum allocation, update the bit allocation, MNR, and bits     */
  1105. /*    available accordingly                         */
  1106. /* 4. Repeat until there are no more bits left, or no more available     */
  1107. /*    subbands. (A subband is still available until the maximum      */
  1108. /*    number of bits for the subband has been allocated, or there     */
  1109. /*    aren't enough bits to go to the next higher resolution in the      */
  1110. /*    subband.)                              */
  1111. /*                                     */
  1112. /*************************************************************************/
  1113.  
  1114. int I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps) /* return noisy sbs */
  1115. double FAR perm_smr[2][SBLIMIT];
  1116. unsigned int bit_alloc[2][SBLIMIT];
  1117. int *adb;
  1118. frame_params *fr_ps;
  1119. {
  1120.    int i, k, smpl_bits, scale_bits, min_sb, min_ch, oth_ch;
  1121.    int bspl, bscf, ad, noisy_sbs, /* done = 0,*/ bbal ;
  1122.    double mnr[2][SBLIMIT], small;
  1123.    char used[2][SBLIMIT];
  1124.    int stereo  = fr_ps->stereo;
  1125. //   int sblimit = fr_ps->sblimit;
  1126.    int jsbound = fr_ps->jsbound;
  1127. //   al_table *alloc = fr_ps->alloc;
  1128. static char init= 0;
  1129. static int banc=32, berr=0;
  1130.  
  1131.    if (!init) {
  1132.       init = 1;
  1133.       if (fr_ps->header->error_protection) berr = 16;  /* added 92-08-11 shn */
  1134.    }
  1135.    bbal = 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
  1136.    *adb -= bbal + berr + banc;
  1137.    ad= *adb;
  1138.  
  1139.    for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++) {
  1140.      mnr[k][i]=snr[0]-perm_smr[k][i];
  1141.      bit_alloc[k][i] = 0;
  1142.      used[k][i] = 0;
  1143.    }
  1144.    bspl = bscf = 0;
  1145.  
  1146.    do  {
  1147.      /* locate the subband with minimum SMR */
  1148.      small = mnr[0][0]+1;    min_sb = -1; min_ch = -1;
  1149.      for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++)
  1150.        /* go on only if there are bits left */
  1151.        if (used[k][i] != 2 && small > mnr[k][i]) {
  1152.      small = mnr[k][i];
  1153.      min_sb = i;  min_ch = k;
  1154.        }
  1155.      if(min_sb > -1) {     /* there was something to find */
  1156.        /* first step of bit allocation is biggest */
  1157.        if (used[min_ch][min_sb])  { smpl_bits = SCALE_BLOCK; scale_bits = 0; }
  1158.        else              { smpl_bits = 24; scale_bits = 6; }
  1159.        if(min_sb >= jsbound)        scale_bits *= stereo;
  1160.  
  1161.        /* check to see enough bits were available for */
  1162.        /* increasing resolution in the minimum band */
  1163.  
  1164.        if (ad >= bspl + bscf + scale_bits + smpl_bits) {
  1165.      bspl += smpl_bits; /* bit for subband sample */
  1166.      bscf += scale_bits; /* bit for scale factor */
  1167.      bit_alloc[min_ch][min_sb]++;
  1168.      used[min_ch][min_sb] = 1; /* subband has bits */
  1169.      mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb]
  1170.                    + snr[bit_alloc[min_ch][min_sb]];
  1171.      /* Check if subband has been fully allocated max bits */
  1172.      if (bit_alloc[min_ch][min_sb] ==  14 ) used[min_ch][min_sb] = 2;
  1173.        }
  1174.        else           /* no room to improve this band */
  1175.      used[min_ch][min_sb] = 2; /*    for allocation anymore */
  1176.        if(stereo == 2 && min_sb >= jsbound) {
  1177.      oth_ch = 1-min_ch;  /* joint-st : fix other ch */
  1178.      bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  1179.      used[oth_ch][min_sb] = used[min_ch][min_sb];
  1180.      mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb]
  1181.                    + snr[bit_alloc[oth_ch][min_sb]];
  1182.        }
  1183.      }
  1184.    } while(min_sb>-1);       /* i.e. still some sub-bands to find */
  1185.  
  1186.    /* Calculate the number of bits left, add on to pointed var */
  1187.    ad -= bspl+bscf;
  1188.    *adb = ad;
  1189.  
  1190.    /* see how many channels are noisy */
  1191.    noisy_sbs = 0; small = mnr[0][0];
  1192.    for(k=0; k<stereo; ++k) {
  1193.      for(i = 0; i< SBLIMIT; ++i) {
  1194.        if(mnr[k][i] < NOISY_MIN_MNR)   ++noisy_sbs;
  1195.        if(small > mnr[k][i])           small = mnr[k][i];
  1196.      }
  1197.    }
  1198.    return noisy_sbs;
  1199. }
  1200.  
  1201. /***************************** Layer II  ********************************/
  1202.  
  1203. int II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
  1204. double FAR perm_smr[2][SBLIMIT];
  1205. unsigned int scfsi[2][SBLIMIT];
  1206. unsigned int bit_alloc[2][SBLIMIT];
  1207. int *adb;
  1208. frame_params *fr_ps;
  1209. {
  1210.    int i, min_ch, min_sb, oth_ch, k, increment, scale, seli, ba;
  1211.    int bspl, bscf, bsel, ad, noisy_sbs, bbal=0;
  1212.    double mnr[2][SBLIMIT], small;
  1213.    char used[2][SBLIMIT];
  1214.    int stereo  = fr_ps->stereo;
  1215.    int sblimit = fr_ps->sblimit;
  1216.    int jsbound = fr_ps->jsbound;
  1217.    al_table *alloc = fr_ps->alloc;
  1218. static char init= 0;
  1219. static int banc=32, berr=0;
  1220. static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
  1221.  
  1222.    if (!init) {
  1223.        init = 1;
  1224.        if (fr_ps->header->error_protection) berr=16; /* added 92-08-11 shn */
  1225.    }
  1226.    for (i=0; i<jsbound; ++i)
  1227.      bbal += stereo * (*alloc)[i][0].bits;
  1228.    for (i=jsbound; i<sblimit; ++i)
  1229.      bbal += (*alloc)[i][0].bits;
  1230.    *adb -= bbal + berr + banc;
  1231.    ad = *adb;
  1232.  
  1233.    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++) {
  1234.      mnr[k][i]=snr[0]-perm_smr[k][i];
  1235.      bit_alloc[k][i] = 0;
  1236.      used[k][i] = 0;
  1237.    }
  1238.    bspl = bscf = bsel = 0;
  1239.  
  1240.    do  {
  1241.      /* locate the subband with minimum SMR */
  1242.      small = 999999.0; min_sb = -1; min_ch = -1;
  1243.      for (i=0;i<sblimit;i++) for(k=0;k<stereo;++k)
  1244.        if (used[k][i]  != 2 && small > mnr[k][i]) {
  1245.      small = mnr[k][i];
  1246.      min_sb = i;  min_ch = k;
  1247.      }
  1248.      if(min_sb > -1) {     /* there was something to find */
  1249.        /* find increase in bit allocation in subband [min] */
  1250.        increment = SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].group *
  1251.             (*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].bits);
  1252.        if (used[min_ch][min_sb])
  1253.      increment -= SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]].group*
  1254.                (*alloc)[min_sb][bit_alloc[min_ch][min_sb]].bits);
  1255.  
  1256.        /* scale factor bits required for subband [min] */
  1257.        oth_ch = 1 - min_ch;    /* above js bound, need both chans */
  1258.        if (used[min_ch][min_sb]) scale = seli = 0;
  1259.        else {           /* this channel had no bits or scfs before */
  1260.      seli = 2;
  1261.      scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
  1262.      if(stereo == 2 && min_sb >= jsbound) {
  1263.        /* each new js sb has L+R scfsis */
  1264.        seli += 2;
  1265.        scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
  1266.      }
  1267.        }
  1268.        /* check to see enough bits were available for */
  1269.        /* increasing resolution in the minimum band */
  1270.        if (ad >= bspl + bscf + bsel + seli + scale + increment) {
  1271.      ba = ++bit_alloc[min_ch][min_sb]; /* next up alloc */
  1272.      bspl += increment;  /* bits for subband sample */
  1273.      bscf += scale;      /* bits for scale factor */
  1274.      bsel += seli;         /* bits for scfsi code */
  1275.      used[min_ch][min_sb] = 1; /* subband has bits */
  1276.      mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb] +
  1277.                    snr[(*alloc)[min_sb][ba].quant+1];
  1278.      /* Check if subband has been fully allocated max bits */
  1279.      if (ba >= (1<<(*alloc)[min_sb][0].bits)-1) used[min_ch][min_sb] = 2;
  1280.        }
  1281.        else used[min_ch][min_sb] = 2; /* can't increase this alloc */
  1282.        if(min_sb >= jsbound && stereo == 2) {
  1283.      /* above jsbound, alloc applies L+R */
  1284.      ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
  1285.      used[oth_ch][min_sb] = used[min_ch][min_sb];
  1286.      mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb] +
  1287.                    snr[(*alloc)[min_sb][ba].quant+1];
  1288.        }
  1289.      }
  1290.    } while(min_sb > -1);   /* until could find no channel */
  1291.    /* Calculate the number of bits left */
  1292.    ad -= bspl+bscf+bsel;   *adb = ad;
  1293.    for (i=sblimit;i<SBLIMIT;i++) for (k=0;k<stereo;k++) bit_alloc[k][i]=0;
  1294.  
  1295.    noisy_sbs = 0;  small = mnr[0][0];       /* calc worst noise in case */
  1296.    for(k=0;k<stereo;++k) {
  1297.      for (i=0;i<sblimit;i++) {
  1298.        if (small > mnr[k][i]) small = mnr[k][i];
  1299.        if(mnr[k][i] < NOISY_MIN_MNR) ++noisy_sbs; /* noise is not masked */
  1300.  
  1301.      }
  1302.    }
  1303.    return noisy_sbs;
  1304. }
  1305.  
  1306. /************************************************************************/
  1307. /*                                    */
  1308. /* I_subband_quantization  (Layer I)                    */
  1309. /* II_subband_quantization (Layer II)                    */
  1310. /*                                    */
  1311. /* PURPOSE:Quantizes subband samples to appropriate number of bits    */
  1312. /*                                    */
  1313. /* SEMANTICS:  Subband samples are divided by their scalefactors, which */
  1314. /* makes the quantization more efficient. The scaled samples are    */
  1315. /* quantized by the function a*x+b, where a and b are functions of    */
  1316. /* the number of quantization levels. The result is then truncated    */
  1317. /* to the appropriate number of bits and the MSB is inverted.        */
  1318. /*                                    */
  1319. /* Note that for fractional 2's complement, inverting the MSB for a     */
  1320. /* negative number x is equivalent to adding 1 to it.            */
  1321. /*                                    */
  1322. /************************************************************************/
  1323.  
  1324. static double a[17] = {
  1325.   0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
  1326.   0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
  1327.   0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
  1328.   0.999969482, 0.999984741 };
  1329.  
  1330. static double b[17] = {
  1331.   -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
  1332.   -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
  1333.   -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
  1334.   -0.000030518, -0.000015259 };
  1335.  
  1336. void I_subband_quantization(scalar, sb_samples, j_scale, j_samps,
  1337.                 bit_alloc, sbband, fr_ps)
  1338. unsigned int scalar[2][3][SBLIMIT];
  1339. double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
  1340. unsigned int j_scale[3][SBLIMIT];
  1341. double FAR j_samps[3][SCALE_BLOCK][SBLIMIT]; /* L+R for j-stereo if necess */
  1342. unsigned int bit_alloc[2][SBLIMIT];
  1343. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1344. frame_params *fr_ps;
  1345. {
  1346.    int i, j, k, n, sig;
  1347.    int stereo  = fr_ps->stereo;
  1348. //   int sblimit = fr_ps->sblimit;
  1349.    int jsbound = fr_ps->jsbound;
  1350.    double d;
  1351. static char init = 0;
  1352.  
  1353.    if (!init) {
  1354.      init = 1;
  1355.      /* rearrange quantization coef to correspond to layer I table */
  1356.      a[1] = a[2]; b[1] = b[2];
  1357.      for (i=2;i<15;i++) { a[i] = a[i+2]; b[i] = b[i+2]; }
  1358.    }
  1359.    for (j=0;j<SCALE_BLOCK;j++) for (i=0;i<SBLIMIT;i++)
  1360.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1361.        if (bit_alloc[k][i]) {
  1362.      /* for joint stereo mode, have to construct a single subband stream
  1363.         for the js channels.  At present, we calculate a set of mono
  1364.         subband samples and pass them through the scaling system to
  1365.         generate an alternate normalised sample stream.
  1366.  
  1367.         Could normalise both streams (divide by their scfs), then average
  1368.         them.  In bad conditions, this could give rise to spurious
  1369.         cancellations.  Instead, we could just select the sb stream from
  1370.         the larger channel (higher scf), in which case _that_ channel
  1371.         would be 'properly' reconstructed, and the mate would just be a
  1372.         scaled version.  Spec recommends averaging the two (unnormalised)
  1373.         subband channels, then normalising this new signal without
  1374.         actually sending this scale factor... This means looking ahead.
  1375.      */
  1376.      if(stereo == 2 && i>=jsbound)
  1377.        /* use the joint data passed in */
  1378.        d = j_samps[0][j][i] / multiple[j_scale[0][i]];
  1379.      else
  1380.        d = sb_samples[k][0][j][i] / multiple[scalar[k][0][i]];
  1381.      /* scale and quantize floating point sample */
  1382.      n = bit_alloc[k][i];
  1383.      d = d * a[n-1] + b[n-1];
  1384.      /* extract MSB N-1 bits from the floating point sample */
  1385.      if (d >= 0) sig = 1;
  1386.      else { sig = 0; d += 1.0; }
  1387.      sbband[k][0][j][i] = (unsigned int) (d * (double) (1L<<n));
  1388.      /* tag the inverted sign bit to sbband at position N */
  1389.      if (sig) sbband[k][0][j][i] |= 1<<n;
  1390.        }
  1391. }
  1392.  
  1393. /***************************** Layer II  ********************************/
  1394.  
  1395. void II_subband_quantization(scalar, sb_samples, j_scale, j_samps,
  1396.                  bit_alloc, sbband, fr_ps)
  1397. unsigned int scalar[2][3][SBLIMIT];
  1398. double FAR sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
  1399. unsigned int j_scale[3][SBLIMIT];
  1400. double FAR j_samps[3][SCALE_BLOCK][SBLIMIT];
  1401. unsigned int bit_alloc[2][SBLIMIT];
  1402. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1403. frame_params *fr_ps;
  1404. {
  1405.    int i, j, k, s, n, qnt, sig;
  1406.    int stereo  = fr_ps->stereo;
  1407.    int sblimit = fr_ps->sblimit;
  1408.    int jsbound = fr_ps->jsbound;
  1409.    unsigned int stps;
  1410.    double d;
  1411.    al_table *alloc = fr_ps->alloc;
  1412.  
  1413.    for (s=0;s<3;s++)
  1414.      for (j=0;j<SCALE_BLOCK;j++)
  1415.        for (i=0;i<sblimit;i++)
  1416.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1417.        if (bit_alloc[k][i]) {
  1418.          /* scale and quantize floating point sample */
  1419.          if(stereo == 2 && i>=jsbound)     /* use j-stereo samples */
  1420.            d = j_samps[s][j][i] / multiple[j_scale[s][i]];
  1421.          else
  1422.            d = sb_samples[k][s][j][i] / multiple[scalar[k][s][i]];
  1423.          if (mod(d) > 1.0)
  1424.            printf("Not scaled properly %d %d %d %d\n",k,s,j,i);
  1425.          qnt = (*alloc)[i][bit_alloc[k][i]].quant;
  1426.          d = d * a[qnt] + b[qnt];
  1427.          /* extract MSB N-1 bits from the floating point sample */
  1428.          if (d >= 0) sig = 1;
  1429.          else { sig = 0; d += 1.0; }
  1430.          n = 0;
  1431. #ifndef MS_DOS
  1432.          stps = (*alloc)[i][bit_alloc[k][i]].steps;
  1433.          while ((1L<<n) < stps) n++;
  1434. #else
  1435.          while  ( ( (unsigned long)(1L<<(long)n) <
  1436.                ((unsigned long) ((*alloc)[i][bit_alloc[k][i]].steps)
  1437.             & 0xffff
  1438.             )
  1439.                ) && ( n <16)
  1440.              ) n++;
  1441. #endif
  1442.          n--;
  1443.          sbband[k][s][j][i] = (unsigned int) (d * (double) (1L<<n));
  1444.          /* tag the inverted sign bit to sbband at position N */
  1445.          /* The bit inversion is a must for grouping with 3,5,9 steps
  1446.         so it is done for all subbands */
  1447.          if (sig) sbband[k][s][j][i] |= 1<<n;
  1448.        }
  1449.        for (s=0;s<3;s++)
  1450.          for (j=sblimit;j<SBLIMIT;j++)
  1451.            for (i=0;i<SCALE_BLOCK;i++) for (k=0;k<stereo;k++) sbband[k][s][i][j] = 0;
  1452. }
  1453.  
  1454. /************************************************************************/
  1455. /*                                    */
  1456. /* I_encode_bit_alloc  (Layer I)                    */
  1457. /* II_encode_bit_alloc (Layer II)                    */
  1458. /*                                    */
  1459. /* PURPOSE:Writes bit allocation information onto bitstream        */
  1460. /*                                    */
  1461. /* Layer I uses 4 bits/subband for bit allocation information,        */
  1462. /* and Layer II uses 4,3,2, or 0 bits depending on the            */
  1463. /* quantization table used.                        */
  1464. /*                                    */
  1465. /************************************************************************/
  1466.  
  1467. void I_encode_bit_alloc(bit_alloc, fr_ps, bs)
  1468. unsigned int bit_alloc[2][SBLIMIT];
  1469. frame_params *fr_ps;
  1470. Bit_stream_struc *bs;
  1471. {
  1472.    int i,k;
  1473.    int stereo  = fr_ps->stereo;
  1474. //   int sblimit = fr_ps->sblimit;
  1475.    int jsbound = fr_ps->jsbound;
  1476.  
  1477.    for (i=0;i<SBLIMIT;i++)
  1478.      for (k=0;k<((i<jsbound)?stereo:1);k++) putbits(bs,bit_alloc[k][i],4);
  1479. }
  1480.  
  1481. /***************************** Layer II  ********************************/
  1482.  
  1483. void II_encode_bit_alloc(bit_alloc, fr_ps, bs)
  1484. unsigned int bit_alloc[2][SBLIMIT];
  1485. frame_params *fr_ps;
  1486. Bit_stream_struc *bs;
  1487. {
  1488.    int i,k;
  1489.    int stereo  = fr_ps->stereo;
  1490.    int sblimit = fr_ps->sblimit;
  1491.    int jsbound = fr_ps->jsbound;
  1492.    al_table *alloc = fr_ps->alloc;
  1493.  
  1494.    for (i=0;i<sblimit;i++)
  1495.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1496.        putbits(bs,bit_alloc[k][i],(*alloc)[i][0].bits);
  1497. }
  1498.  
  1499. /************************************************************************/
  1500. /*                                    */
  1501. /* I_sample_encoding   (Layer I)                    */
  1502. /* II_sample_encoding  (Layer II)                    */
  1503. /*                                    */
  1504. /* PURPOSE:Put one frame of subband samples on to the bitstream     */
  1505. /*                                    */
  1506. /* SEMANTICS:  The number of bits allocated per sample is read from    */
  1507. /* the bit allocation information #bit_alloc#.    Layer 2         */
  1508. /* supports writing grouped samples for quantization steps        */
  1509. /* that are not a power of 2.                        */
  1510. /*                                    */
  1511. /************************************************************************/
  1512.  
  1513. void I_sample_encoding(sbband, bit_alloc, fr_ps, bs)
  1514. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1515. unsigned int bit_alloc[2][SBLIMIT];
  1516. frame_params *fr_ps;
  1517. Bit_stream_struc *bs;
  1518. {
  1519.    int i,j,k;
  1520.    int stereo  = fr_ps->stereo;
  1521. //   int sblimit = fr_ps->sblimit;
  1522.    int jsbound = fr_ps->jsbound;
  1523.  
  1524.    for(j=0;j<SCALE_BLOCK;j++) {
  1525.      for(i=0;i<SBLIMIT;i++)
  1526.        for(k=0;k<((i<jsbound)?stereo:1);k++)
  1527.      if(bit_alloc[k][i]) putbits(bs,sbband[k][0][j][i],bit_alloc[k][i]+1);
  1528.    }
  1529. }
  1530.  
  1531. /***************************** Layer II  ********************************/
  1532.  
  1533. void II_sample_encoding(sbband, bit_alloc, fr_ps, bs)
  1534. unsigned int FAR sbband[2][3][SCALE_BLOCK][SBLIMIT];
  1535. unsigned int bit_alloc[2][SBLIMIT];
  1536. frame_params *fr_ps;
  1537. Bit_stream_struc *bs;
  1538. {
  1539.    unsigned int temp;
  1540.    unsigned int i,j,k,s,x,y;
  1541.    int stereo  = fr_ps->stereo;
  1542.    int sblimit = fr_ps->sblimit;
  1543.    int jsbound = fr_ps->jsbound;
  1544.    al_table *alloc = fr_ps->alloc;
  1545.  
  1546.    for (s=0;s<3;s++)
  1547.      for (j=0;j<SCALE_BLOCK;j+=3)
  1548.        for (i=0;i<sblimit;i++)
  1549.      for (k=0;k<((i<jsbound)?stereo:1);k++)
  1550.        if (bit_alloc[k][i]) {
  1551.          if ((*alloc)[i][bit_alloc[k][i]].group == 3) {
  1552.            for (x=0;x<3;x++) putbits(bs,sbband[k][s][j+x][i],
  1553.                      (*alloc)[i][bit_alloc[k][i]].bits);
  1554.          }
  1555.          else {
  1556.            y =(*alloc)[i][bit_alloc[k][i]].steps;
  1557.            temp = sbband[k][s][j][i] +
  1558.               sbband[k][s][j+1][i] * y +
  1559.               sbband[k][s][j+2][i] * y * y;
  1560.            putbits(bs,temp,(*alloc)[i][bit_alloc[k][i]].bits);
  1561.          }
  1562.        }
  1563. }
  1564.  
  1565. /************************************************************************/
  1566. /*                                    */
  1567. /* encode_CRC                                */
  1568. /*                                    */
  1569. /************************************************************************/
  1570.  
  1571. void encode_CRC(crc, bs)
  1572. unsigned int crc;
  1573. Bit_stream_struc *bs;
  1574. {
  1575.    putbits(bs, crc, 16);
  1576. }
  1577.